package com.example.memo2.utils

import android.content.Context
import android.media.MediaPlayer
import android.media.MediaRecorder
import android.os.Build
import java.io.IOException

class AudioManager(private val context: Context) {
    
    private var mediaRecorder: MediaRecorder? = null
    private var mediaPlayer: MediaPlayer? = null
    private var isRecording = false
    private var isPlaying = false
    private var currentAudioFile: String? = null
    
    // 回调接口
    interface AudioCallback {
        fun onRecordingStarted()
        fun onRecordingStopped(filePath: String)
        fun onRecordingError(error: String)
        fun onPlaybackStarted()
        fun onPlaybackCompleted()
        fun onPlaybackError(error: String)
    }
    
    private var callback: AudioCallback? = null
    
    fun setAudioCallback(callback: AudioCallback) {
        this.callback = callback
    }
    
    /**
     * 开始录音
     */
    fun startRecording(): String? {
        if (isRecording) return null
        
        val audioFilePath = MediaUtils.generateAudioFilePath(context)
        
        try {
            mediaRecorder = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
                MediaRecorder(context)
            } else {
                @Suppress("DEPRECATION")
                MediaRecorder()
            }
            
            mediaRecorder?.apply {
                setAudioSource(MediaRecorder.AudioSource.MIC)
                setOutputFormat(MediaRecorder.OutputFormat.MPEG_4)
                setAudioEncoder(MediaRecorder.AudioEncoder.AAC)
                setOutputFile(audioFilePath)
                
                prepare()
                start()
            }
            
            isRecording = true
            currentAudioFile = audioFilePath
            callback?.onRecordingStarted()
            
            return audioFilePath
        } catch (e: IOException) {
            e.printStackTrace()
            callback?.onRecordingError("Recording failed to start: ${e.message}")
            return null
        }
    }
    
    /**
     * 停止录音
     */
    fun stopRecording(): String? {
        if (!isRecording || mediaRecorder == null) return null
        
        return try {
            mediaRecorder?.apply {
                stop()
                release()
            }
            mediaRecorder = null
            isRecording = false
            
            val filePath = currentAudioFile
            if (filePath != null) {
                callback?.onRecordingStopped(filePath)
            }
            filePath
        } catch (e: Exception) {
            e.printStackTrace()
            callback?.onRecordingError("Recording failed to stop: ${e.message}")
            null
        }
    }
    
    /**
     * 播放音频
     */
    fun playAudio(filePath: String) {
        if (isPlaying) {
            stopPlayback()
        }
        
        try {
            mediaPlayer = MediaPlayer().apply {
                setDataSource(filePath)
                prepareAsync()
                
                setOnPreparedListener {
                    start()
                    this@AudioManager.isPlaying = true
                    this@AudioManager.callback?.onPlaybackStarted()
                }
                
                setOnCompletionListener {
                    this@AudioManager.isPlaying = false
                    this@AudioManager.callback?.onPlaybackCompleted()
                }
                
                setOnErrorListener { _, what, extra ->
                    this@AudioManager.isPlaying = false
                    this@AudioManager.callback?.onPlaybackError("Playback error: what=$what, extra=$extra")
                    true
                }
            }
        } catch (e: IOException) {
            e.printStackTrace()
            callback?.onPlaybackError("Playback failed: ${e.message}")
        }
    }
    
    /**
     * 停止播放
     */
    fun stopPlayback() {
        if (isPlaying && mediaPlayer != null) {
            try {
                mediaPlayer?.stop()
                isPlaying = false
                callback?.onPlaybackCompleted()
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
        
        mediaPlayer?.release()
        mediaPlayer = null
    }
    
    /**
     * 暂停播放
     */
    fun pausePlayback() {
        if (isPlaying && mediaPlayer?.isPlaying == true) {
            mediaPlayer?.pause()
            isPlaying = false
            callback?.onPlaybackCompleted()
        }
    }
    
    /**
     * 释放资源
     */
    fun release() {
        stopRecording()
        stopPlayback()
    }
    
    /**
     * 检查状态
     */
    fun isRecording(): Boolean = isRecording
    fun isPlaying(): Boolean = isPlaying
} 